package com.moon.game.server;

import static org.jboss.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST;
import static org.jboss.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR;

import org.apache.log4j.Logger;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.handler.codec.frame.TooLongFrameException;
import org.jboss.netty.handler.codec.http.HttpResponseStatus;

import com.moon.game.command.Command;
import com.moon.game.constants.Constants;
import com.moon.game.manager.PlayerMG;
import com.moon.game.message.ObjMessage;
import com.moon.game.server.SessionPool.UniData;

/**
 * HTTP
 * 
 * @author sky
 * 
 */
public class DataGramHandler extends SimpleChannelUpstreamHandler {

	private static final Logger log = Logger.getLogger(DataGramHandler.class);
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
			throws Exception {
		Channel ch = e.getChannel();
		Throwable cause = e.getCause();
		if (cause instanceof TooLongFrameException) {
			sendError(ctx, BAD_REQUEST);
			return;
		}
		cause.printStackTrace();
		if (ch.isConnected()) {
			sendError(ctx, INTERNAL_SERVER_ERROR);
		}
		ch.close();
	}
	
	private void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) throws Exception {
//		NettyUtil.outErrorMsg(ctx, MessageResource.buildMsg(ErrorCode.ERR_SYS));
		System.out.println("错误信息");
	}

	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
			throws Exception {
		ObjMessage data = (ObjMessage) e.getMessage();
		if (PlayerMG.instance.checkLock(data.getPid()) && !"LOG_IN".equals(data.getCmd()) && !"P_VM".equals(data.getCmd())) {
			//TODO：返回让玩家慢一点
			ObjMessage resp = new ObjMessage();
			resp.setStatus(Constants.STATUS_FAIL);
			resp.setCmd("E_TF");
			resp.setPid(data.getPid());
			resp.setSid(data.getSid());
			resp.setVO(Command.PAR_ID, data.getPid());
			resp.setVO(Command.TAG_ERR_MSG, "您可以慢一点么...");
			e.getChannel().write(resp,e.getRemoteAddress());
			return;
		}
		if (!"LOG_IN".equals(data.getCmd()) && !"P_VM".equals(data.getCmd())) {
			PlayerMG.instance.lock(data.getPid());
		}
		SessionPool.UniData unidata = new SessionPool.UniData(UniData.FROM_CLIENT,data,e);
		SessionPool.inst.addData(unidata);
	}
	
	/*private void handleRequest(MessageEvent e, ObjMessage data) {
		PlayerMG.instance.lock(data.getPid());
		SessionPool.UniData unidata = new SessionPool.UniData(UniData.FROM_CLIENT,data,e);
		SessionPool.inst.addData(unidata);
		log.info("add data");
	}*/
}
